<template>
  <div :id="id" :class="className" :style="{height:height,width:width}" />
</template>

<script>
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    title: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    chartDataKey: {
      type: Object,
      default: () => {
        return {
          name: 'name',
          value: 'value'
        }
      }
    },
    chartData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null,
      chartOptions: {
        title: {
          text: this.title || '',
          subtext: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          bottom: 10,
          align: 'auto'
        },
        series: [
          {
            name: this.title || '',
            type: 'pie',
            radius: '40%',
            center: ['50%', '50%'],
            label: {
              normal: {
                formatter: '{b}({d}%)',
                textStyle: {
                  fontSize: 12
                }
              }
            },
            data: []
          }
        ]
      }
    }
  },

  watch: {
    chartData: function() {
      this.fetchChart()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.fetchChart()
    })
  },

  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    /**
     * 获取数据
     */
    // 初始化图表
    fetchChart() {
      this.formatChartData()
      this.chart = this.$echarts.init(document.getElementById(this.id))
      this.chart.setOption(this.chartOptions)
    },

    /**
     * 方法组
     */
    // 格式化图表数据
    formatChartData() {
      const seriesData = JSON.parse(JSON.stringify(this.chartData))
      seriesData.forEach(item => {
        item.name = item[this.chartDataKey.name]
        item.value = item[this.chartDataKey.value]
      })
      this.chartOptions.series[0].data = seriesData
    }
  }
}
</script>
